package com.xbongbong.saas.model.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.domain.dao.StaticForMarketActivityDao;
import com.xbongbong.saas.domain.entity.StaticForMarketActivityEntity;
import com.xbongbong.saas.domain.entity.StaticForMarketUpdateEntity;
import com.xbongbong.saas.model.MarketActivityForStaticModel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author guohui.zhang
 * @Title:
 * @date 2020/12/1815:46
 */
@Service("marketActiviryForStaticModel")
public class MarketActivityForStaticModelImpl implements MarketActivityForStaticModel {
    private static final Logger LOG = LoggerFactory.getLogger(MarketActivityForStaticModelImpl.class);
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private StaticForMarketActivityDao staticForMarketActivityDao;

    @Override
    public Integer insert(StaticForMarketActivityEntity entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        entity.setDel(DelEnum.NORMAL.getDel());
        Integer insert = staticForMarketActivityDao.insert(entity);
        InsertDTO saveDTO = getSaveDTO(entity, IndexTypeEnum.IDX_STATICS_MARKET_DATA);
        paasEsModel.insert(saveDTO);
        return insert;
    }

    @Override
    public Integer update(StaticForMarketActivityEntity entity) throws XbbException {
        return null;
    }

    @Override
    public List findEntitys(Map<String, Object> param) {
        return staticForMarketActivityDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return null;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public void insertBatch(List<StaticForMarketActivityEntity> list, String corpid) throws XbbException {
        if (CollectionsUtil.isEmpty(list)) {
            return;
        }
        long now = DateUtil.getInt();
        list.forEach(item -> {
            item.setUpdateTime(now);
            item.setAddTime(now);
            item.setCorpid(corpid);
            if(Objects.isNull(item.getDel())){
                item.setDel(DelEnum.NORMAL.getDel());
            }
        });
        staticForMarketActivityDao.insertBatch(list);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (StaticForMarketActivityEntity item : list) {
            insertList.add( getSaveDTO(item, IndexTypeEnum.IDX_STATICS_MARKET_DATA));
        }
        paasEsModel.insertBatch(insertList);
    }

    @Override
    public Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException {
        if (CollectionsUtil.isEmpty(list)) {
            return 0;
        }
        Integer integer = staticForMarketActivityDao.deleteBatch(list, corpid, del);
        paasEsModel.deleteBatch(list, corpid, del, IndexTypeEnum.IDX_STATICS_MARKET_DATA);
        return integer;
    }
    @Override
    public Integer updateByMarketIdAndDel(List<Long> idList,String corpid, Long marketId,Integer del) throws XbbException {
        Integer integer = staticForMarketActivityDao.updateByMarketIdAndDel(corpid, marketId,del);
        HttpEntity httpEntity = null;
        try {
            httpEntity = new NStringEntity("{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"corpid.keyword\":\"" + corpid + "\"}},{\"term\":{\"marketId\":\"" + marketId + "\"}}]}}}, \"script\": {\"source\": \"ctx._source['del'] = params['del']\",\"params\": {\"del\": "+del+"}}", ContentType.APPLICATION_JSON);
            String index = IndexTypeEnum.IDX_STATICS_MARKET_DATA.getIndex();
            Request request = new Request("POST",index + "/_update_by_query");
            request.setEntity(httpEntity);
            xbbElasticsearchRestTemplate.getRestClient(index).performRequest(request);
        } catch (Exception e) {
            LOG.error("",e);
        } finally {
            if (Objects.nonNull(httpEntity)) {
                try {
                    ((NStringEntity) httpEntity).close();
                } catch (Exception e) {
                    LOG.error("MarketActivityForStaticModelImpl.updateByMarketIdAndDel",e);
                }
            }
        }
//        paasEsModel.updateByMarketIdAndDel(idList, corpid,IndexTypeEnum.IDX_STATICS_MARKET_DATA,del);
        return integer;
    }
    @Override
    public Integer deleteByMarketId(List<Long> idList,String corpid, Long marketId) throws XbbException {
        Integer integer = staticForMarketActivityDao.deleteByMarketId(corpid, marketId);
//        paasEsModel.physicalDeleteBatch(idList, corpid, IndexTypeEnum.IDX_STATICS_MARKET_DATA);
        HttpEntity httpEntity = null;
        try {
            httpEntity = new NStringEntity("{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"corpid.keyword\":\"" +
                    corpid +
                    "\"}},{\"term\":{\"marketId\":\""+marketId+"\"}}]}}}", ContentType.APPLICATION_JSON);
            String index = IndexTypeEnum.IDX_STATICS_MARKET_DATA.getIndex();
            Request request = new Request("POST", index + "/_delete_by_query");
            request.setEntity(httpEntity);
            xbbElasticsearchRestTemplate.getRestClient(index).performRequest(request);
        } catch (Exception e) {
            LOG.error("", e);
        } finally {
            if ( Objects.nonNull(httpEntity) ) {
                try {
                    ((NStringEntity) httpEntity).close();
                } catch (Exception e) {
                    LOG.error("dataWarehouse.deleteByQuery", e);
                }
            }
        }
        return integer;
    }
    
    @Override
    public void updateBatch(List<StaticForMarketUpdateEntity> list, String corpid) throws XbbException {
        staticForMarketActivityDao.updateBatch(list, corpid);
        updateStaticBatch(list, IndexTypeEnum.IDX_STATICS_MARKET_DATA);
    }

    @Override
    public StaticForMarketActivityEntity getByMarketId(Long key, String corpid)throws XbbException {
        return staticForMarketActivityDao.getByMarketId(key , corpid);
    }

    @Override
    public StaticForMarketActivityEntity getByClueId(Long key, String corpid) throws XbbException{
        return staticForMarketActivityDao.getByClueId(key , corpid);
    }

    @Override
    public StaticForMarketActivityEntity getByCustomerId(Long key, String corpid)throws XbbException {
        return staticForMarketActivityDao.getByCustomerId(key , corpid);
    }

    @Override
    public StaticForMarketActivityEntity getBySaleId(Long key, String corpid) throws XbbException{
        return staticForMarketActivityDao.getBySaleId(key , corpid);
    }

    @Override
    public void updateBatchForStatic(List<StaticForMarketActivityEntity> updateEntitys) throws XbbException {
        if (CollectionsUtil.isEmpty(updateEntitys)) {
            return;
        }
        staticForMarketActivityDao.updateBatchForStatic(updateEntitys);
        List<InsertDTO> insertList = new ArrayList<>();
        for (StaticForMarketActivityEntity item : updateEntitys) {
            insertList.add( getSaveDTO(item, IndexTypeEnum.IDX_STATICS_MARKET_DATA));
        }
//        paasEsModel.insertBatch(insertList);
        paasEsModel.updateBatch(insertList);
    }

    @Override
    public List<StaticForMarketActivityEntity> getEntitysForClueDeduplication(Long customerId, String corpid) throws XbbException {
        return staticForMarketActivityDao.getEntitysForClueDeduplication(customerId, corpid);
    }

    @Override
    public List<StaticForMarketActivityEntity> getEntitysForCustomerDeduplication(Long customerId, String corpid) throws XbbException {
        return staticForMarketActivityDao.getEntitysForCustomerDeduplication(customerId, corpid);
    }

    @Override
    public List<StaticForMarketActivityEntity> getEntitysForOpportunityDeduplication(Long opportunityId, String corpid) throws XbbException {
        return staticForMarketActivityDao.getEntitysForOpportunityDeduplication(opportunityId, corpid);
    }


    private InsertDTO getSaveDTO(StaticForMarketActivityEntity entity, IndexTypeEnum indexTypeEnum) throws XbbException {
        InsertDTO insertDTO = new InsertDTO();
        insertDTO.setEsId(entity.getCorpid() + "_" + entity.getId());
        entity.setDataId(entity.getId());
        Map<String, Object> source = BeanUtil.convertBean2Map(entity, true, true);
        source.remove("id");
        insertDTO.setSource(source);
        insertDTO.setIndexTypeEnum(indexTypeEnum);
        return insertDTO;
    }

    /**
     *
     * date: 2022/3/14 8:51 上午
     * @Author yingjf
     * @param list:
     * @param indexTypeEnum:
     */
    private void updateStaticBatch(List<StaticForMarketUpdateEntity> list, IndexTypeEnum indexTypeEnum) throws XbbException {
        List<InsertDTO> insertList = new ArrayList<>();
        for (StaticForMarketUpdateEntity entity : list) {
            InsertDTO insertDTO = new InsertDTO();
            Map<String,Object> source= new HashMap(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(entity.getMarketId())) {
                source.put("marketId",entity.getMarketId());
            }
            if (Objects.nonNull(entity.getMarketEndTime())) {
                source.put("marketEndTime",entity.getMarketEndTime());
            }
            if (Objects.nonNull(entity.getMarketName())) {
                source.put("marketName",entity.getMarketName());
            }
            if (Objects.nonNull(entity.getMarketType())) {
                source.put("marketType",entity.getMarketType());
            }
            if (Objects.nonNull(entity.getActualCost())) {
                source.put("actualCost",entity.getActualCost());
            }
            if (Objects.nonNull(entity.getClueId())) {
                source.put("clueId",entity.getClueId());
            }
            if (Objects.nonNull(entity.getClueStage())) {
                source.put("clueStage",entity.getClueStage());
            }
            if (Objects.nonNull(entity.getClueAddTime())) {
                source.put("clueAddTime",entity.getClueAddTime());
            }
            if (Objects.nonNull(entity.getClueStatus())) {
                source.put("clueStatus",entity.getClueStatus());
            }
            if (Objects.nonNull(entity.getSaleMoney())) {
                source.put("saleMoney",entity.getSaleMoney());
            }
            if (Objects.nonNull(entity.getSaleStage())) {
                source.put("saleStage",entity.getSaleStage());
            }
            if (Objects.nonNull(entity.getCustomerId())){
                source.put("customerId",entity.getCustomerId());
            }
            if (Objects.nonNull(entity.getSaleOpportunityId())){
                source.put("saleOpportunityId", entity.getSaleOpportunityId());
            }
            if (Objects.nonNull(entity.getContractMoney())){
                source.put("contractMoney", entity.getContractMoney());
            }
            if (Objects.nonNull(entity.getDel())) {
                source.put("del",entity.getDel());
            }


            insertDTO.setSource(source);
            insertDTO.setIndexTypeEnum(indexTypeEnum);
            insertDTO.setEsId(entity.getCorpid()+"_"+entity.getId());
            insertList.add(insertDTO);
        }
        // fix 加个不等待  这里不等待es的请求返回，因为本身就是在异步线程里 防止es占用线程时间长
        paasEsModel.updateBatch(insertList, WriteRequest.RefreshPolicy.NONE);
    }

}
